import { Table, Button, Modal, Form, Input } from "antd"
import { useQuery, useLazyQuery, useMutation } from "@apollo/client"
import { SEARCH_USER_ID, USER_LIST, USER_UPDATE_INFO, USER_ADD_INFO } from "../../schema/user"
import { useBoolean, useSetState } from "ahooks"
import { forMatTime } from "../../utils/formatTime"
import { PlusOutlined } from "@ant-design/icons"
const { useForm } = Form;
const UserPages = () => {
  const [ searchUserId ] = useLazyQuery(SEARCH_USER_ID);
  const [ pageData, setPageData ] = useSetState({
    limit: 5,
    page: 1
  })
  const { loading, data, error, refetch } = useQuery(USER_LIST, {
    variables: {
      ...pageData
    }
  })
  const [ visible, {setTrue, setFalse} ] = useBoolean(false);
  const [ updateUserInfo ] = useMutation(USER_UPDATE_INFO);
  const [ createUser ] = useMutation(USER_ADD_INFO);
  const [modelForm] = useForm();
  const [ modalData, setModalData ] = useSetState({
    title: '弹窗标题',
    data: {
      id: '',
      name:'',
      age:'',
      created_at: '',
      updated_at: ''
    }
  })
  if (error) return <p>error :( {console.error(error)}</p>;
  // console.log(data);
  const handleEdit = async (id) => {
    const { data: {user} } = await searchUserId({
      variables: {id}
    })
    setModalData({title: '编辑', data: user})
    setTrue()
    // console.log(data);
    modelForm.setFieldsValue(user)
  }
  const handleModelOk = async () => {
    if(modalData.title === '新增'){
      await createUser({
        variables: {
          data:{
            ...modelForm.getFieldsValue()
          }
        }
      })
    }else {
      await updateUserInfo({
        variables: {
          id: modalData.data.id,
          data: {
            ...modelForm.getFieldsValue()
          }
        }
      })
    }
    setFalse()
    refetch();
  }
  const hanldeAddShowModel = () => {
    setTrue()
    setModalData({title: '新增', data: {}})
    modelForm.resetFields()
  }
  const handlePageChange = (page) => {
    setPageData({page})
    refetch({
      page
    })
  }
  const columns = [
    {
      title: 'id',
      dataIndex: 'id'
    },
    {
      title: '用户名',
      dataIndex: 'name'
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      render(text, value){
        return <span>{forMatTime(value.created_at)}</span>
      }
    },
    {
      title: '操作',
      render(text, value){
        return (
          <>  
            <Button type="link" onClick={() => handleEdit(value.id)}>编辑</Button>
            <Button type="link">删除</Button>
          </>
        )
      }
    }
  ];
  return (
    <div>
      <h2>用户管理</h2>
      <Modal
        title={modalData.title}
        visible={visible}
        onCancel={setFalse}
        onOk={handleModelOk}
      >
        <Form
          form={modelForm}
        >
          <Form.Item name="name" label="姓名">
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item name="age" label="年龄">
            <Input placeholder="请输入年龄" />
          </Form.Item>
        </Form>
      </Modal>
      <Form>
        <Form.Item>
          <Button icon={<PlusOutlined />} type="primary" onClick={hanldeAddShowModel}>新增</Button>
        </Form.Item>
      </Form>
      <Table 
        loading={loading}
        bordered
        rowKey={"id"}
        columns={columns}
        dataSource={data?.userList?.data}
        pagination={{
          pageSize: pageData.limit,
          current: pageData.page,
          total: data?.userList?.total,
          onChange: handlePageChange
        }}
      />
    </div>
  )
}

export default UserPages;